package com.i2863.receipt.controller;

import com.i2863.receipt.entity.Activity;
import com.i2863.receipt.entity.Prize;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.entity.Winner;
import com.i2863.receipt.service.ActivityService;
import com.i2863.receipt.service.PrizeService;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.service.WinnerService;
import com.i2863.receipt.util.ExcelUtil;
import com.i2863.receipt.util.ResultJson;
import com.i2863.receipt.vo.PrizeVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * Created by Administrator on 2018/6/8.
 */
@Controller
@RequestMapping("/winner")
public class WinnerController {

    @Autowired
    private WinnerService winnerService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private PrizeService prizeService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;



    private static int PAGESIZE = 10;


    /**
     * 中奖列表
     * @param modelMap
     * @param startTime 起始时间
     * @param endTime 截止时间
     * @param pageNum 页码
     * @param activityId 活动id
     * @param queryContent 查询关键字（中奖者手机号）
     * @return
     */
    @RequestMapping("/getlist")
    public String getlist(ModelMap modelMap,
                          @RequestParam(value = "startTime",required = false)String startTime,
                          @RequestParam(value = "endTime",required = false)String endTime,
                          @RequestParam(value = "pageNum",required = false,defaultValue = "1")Integer pageNum,
                          @RequestParam(value = "activityId",required = false)Integer activityId,
                          @RequestParam(value = "queryContent",required = false)String queryContent,
                          @RequestParam(value = "prizeLevel",required = false)Integer prizeLevel){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        List<Activity> activities = activityService.findListBySiteId(siteId);
        Page<Winner> page = winnerService.queryByPage(queryContent,startTime,endTime,activityId,pageNum,PAGESIZE,siteId,prizeLevel);
        List<Winner> list = page.getContent();
        List<Prize> prizeList = prizeService.groupPrizeByLevel(siteId);
        modelMap.put("list",list);
        modelMap.put("total",page.getTotalElements());
        modelMap.put("pageNum",pageNum);
        modelMap.put("startTime",startTime);
        modelMap.put("endTime",endTime);
        modelMap.put("activityId",activityId);
        modelMap.put("prizeLevel",prizeLevel);
        modelMap.put("prizeList",prizeList);
        modelMap.put("queryContent",queryContent);
        modelMap.put("activities",activities);
        modelMap.put("pageSize",PAGESIZE);
        return "winner/list";
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public String del(@RequestParam(value = "ids")String ids){
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            winnerService.del(Integer.parseInt(id));
        }
        return ResultJson.successMeg("删除完成");
    }

    /**
     * 跳转添加页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(ModelMap modelMap){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        List<Prize> prizeList = prizeService.findBySiteId(siteId);
        List<Activity> activityList = activityService.findListBySiteId(siteId);
        modelMap.put("prizeList",prizeList);
        List<PrizeVo> prizeVoList = new ArrayList<PrizeVo>();
        //vo转换
        for (Prize prize : prizeList) {
            String name = prize.getName();
            if(StringUtils.isNotBlank(prize.getPrizeName())){
                name+=prize.getPrizeName();
            }
            if(prize.getPrizeRange()==1){
                name+="(场内)";
            }else{
                name+="(未入围)";
            }

            PrizeVo vo = new PrizeVo();
            vo.setId(prize.getId());
            vo.setName(name);
            prizeVoList.add(vo);
        }
        modelMap.put("prizeVoList",prizeVoList);
        modelMap.put("activityList",activityList);
        return "winner/add";
    }

    @RequestMapping("/save")
    @ResponseBody
    public String save(Winner winner,
                       @RequestParam(value = "receiptTime",required = true)String receiptTime,
                       @RequestParam(value = "prizeId",required = true)Integer prizeId){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Site site = siteService.findOne(siteId);
        winner.setSite(site);
        Prize prize = prizeService.findOne(prizeId);

        Winner entity = winnerService.findWinnerByActivity_IdAndReceiptCode(winner.getReceiptCode(),winner.getActivity().getId());
        if(entity==null){
            return ResultJson.errorMes("该发票并未入围");
        }
        winner.setLevelName(prize.getName());
        winner.setLevel(prize.getLevel());
        winner.setPrize(prize.getPrize());
        winner.setPrizeName(prize.getPrizeName());
        winner.setMoney(prize.getMoney());
//        winner.setIsReselection();
        Integer range = prize.getPrizeRange();
        if(range==1){//奖项范围为场内
            winner.setIsReselection(false);
            winner.setIsInside(true);
        }else{
            winner.setIsInside(false);
            winner.setIsReselection(true);
        }
        Date receiptDate = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            receiptDate = format.parse(receiptTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        winner.setReceiptDate(receiptDate);
        winnerService.updateWinner(winner);
        return ResultJson.successMeg("添加成功");
    }


    /**
     * 按条件查询并导出Excel
     * @param startTime
     * @param endTime
     * @param activityId
     * @param queryContent
     * @return
     */
    @RequestMapping("/exportexcel")
    @ResponseBody
    public void exportexcel(@RequestParam(value = "startTime",required = false)String startTime,
                              @RequestParam(value = "endTime",required = false)String endTime,
                              @RequestParam(value = "activityId",required = false)Integer activityId,
                              @RequestParam(value = "queryContent",required = false)String queryContent,
                            @RequestParam(value = "prizeLevel",required = false)Integer prizeLevel){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        List<Winner> winnerList = winnerService.queryList(startTime,endTime,activityId,queryContent,siteId,prizeLevel);
        //excel标题
        String[] title = {"中奖人电话", "发票号码", "发票代码", "发票金额", "发票日期", "奖品名称","中奖金额","奖项名称","是否场内","是否入围","活动期数"};

        //excel文件名
        String fileName = "中奖信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "中奖信息表";

        String[][] content = new String[winnerList.size()][];

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < winnerList.size(); i++) {
            content[i] = new String[title.length];
            Winner obj = winnerList.get(i);
            content[i][0] = obj.getWinPhoneNum().toString();
            content[i][1] = obj.getReceiptCode().toString();
            content[i][2] = obj.getReceiptCodeNum().toString();
            content[i][3] = obj.getReceiptMoney().toString();
            content[i][4] = format.format(obj.getReceiptDate());
            if(StringUtils.isNotBlank(obj.getLevelName())){
                content[i][5] = obj.getLevelName();
            }else{
                content[i][5] = "";
            }
            if(obj.getMoney()!=null){
                content[i][6] = obj.getMoney().toString();
            }else{
                content[i][6] = "";
            }
            if(StringUtils.isNotBlank(obj.getPrizeName())){
                content[i][7] = obj.getPrizeName();
            }else{
                content[i][7] = "";
            }
            if(obj.getIsInside()!=null){
                if(obj.getIsInside()){
                    content[i][8] = "是";
                }else{
                    content[i][8] = "否";
                }
            }else{
                content[i][8] = "";
            }
            if(obj.getIsReselection()!=null){
                if(obj.getIsReselection()){
                    content[i][9] = "否";
                }else{
                    content[i][9] = "是";
                }
            }else{
                content[i][9] = "";
            }
            content[i][10] = obj.getActivity().getNum().toString();

        }


        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            }



    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1")+".xls");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
